package com.zhj.springbootinit.utils;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Excel 相关工具类
 */
@Slf4j
public class ExcelUtils {

    /**
     * EXCEL -> CSV
     * @param multipartFile
     * @return
     */

    public static String ExcelToCsv(MultipartFile multipartFile) {
        // 读的是死文件，需要改
//        File file = null;
//        try {
//            file = ResourceUtils.getFile("classpath:web_data.xlsx");
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
        // [{0=时间, 1=用户量, 2=null, 3=null}, {0=1, 1=10, 2=null, 3=null}, {0=2, 1=20}, {0=4, 1=40}]
        List<Map<Integer, String>> list = null;
        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            log.error("表格处理错误", e);
            e.printStackTrace();
        }

        // 校验 是否有数据
        if (CollUtil.isEmpty(list)) return "";

        // 容器，拼接存放处理后的文本
        StringBuilder result = new StringBuilder();
        // 处理表头
        LinkedHashMap<Integer, String> headMap = (LinkedHashMap) list.get(0);
        List<String> processedHeadList = headMap.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
//        System.out.println(StringUtils.join(processedHeadList, ","));
        result.append(StringUtils.join(processedHeadList, ",")).append("\n");
        // 处理数据
        for (int i = 1; i < headMap.size(); i++) {
            LinkedHashMap<Integer, String> childMap = (LinkedHashMap) list.get(i);
            List<String> processedChildList = childMap.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
//            System.out.println(StringUtils.join(processedChildList, ","));
            result.append(StringUtils.join(processedChildList, ",")).append("\n");
        }

//        System.out.println(result.toString());
        return result.toString();

    }

    public static void main(String[] args) throws FileNotFoundException {
        ExcelUtils.ExcelToCsv(null);
    }
}
